package com.jky.trial.controller;

import com.jky.trial.annotation.NoRepeatSubmit;
import com.jky.trial.common.BaseResult;
import com.jky.trial.common.Constants;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.jwt.JWTUtil;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.constant.PermissionConstant;
import com.jky.trial.entity.Category;
import com.jky.trial.entity.User;
import com.jky.trial.service.CategoryService;
import com.jky.trial.service.LogService;
import com.jky.trial.service.UserService;
import com.jky.trial.vo.CategoryVo;
import com.jky.trial.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/user")
@RequiredArgsConstructor
public class UserController {

//    private static final String template = "Hello, %s!";
//    private final AtomicLong counter = new AtomicLong();
    private static final Logger _logger = LoggerFactory.getLogger(UserController.class);

    CategoryService categoryService;
    UserService userService;
    LogService logService;

    @Autowired
    UserController(UserService userService,LogService logService,CategoryService categoryService) {
        this.userService = userService;
        this.categoryService= categoryService;
        this.logService =logService;
    }

    @PostMapping("/login")
    public BaseResult login(@RequestBody User record, HttpServletRequest request) {
        _logger.info("用户请求登录获取Token");
        record.setStatus(DataStatus.LOGIC_EXISTS_STATUS.getVal());
        if (record.getUserName() == null || record.getPassword() == null) return new BaseResult(false, "用户名或密码错误！");
        String password = record.getPassword();
        record.setPassword(null);
        record.setStatus(1);//异常状态
        record.setDeleted(false);
        User user = userService.findOne(record);
        if (user == null) return new BaseResult(false, "用户名密码错误或账户已经停用");

        if (user.getDeleted())
            return new BaseResult(false, "账号状态异常，请联系管理员！");

        if (!user.getPassword().equals(password)) return new BaseResult(false, "用户名或密码错误！");
        Map<String,String> res =new HashMap();
        res.put("token",JWTUtil.sign(user,password));
        logService.log(
                DataStatus.LOG_DATA_TYPE_LOGIN_LOG.getVal(),
                "登录,访问IP"+Constants.getIP(request),
                user.getId(),
                user.getId()
                );
        user.setPassword(null);
        if(user.getTechRegId()==null){
            user.setTechRegId(record.getTechRegId());
            userService.update(user);
        }else if(user.getDescRegId()==null){
            user.setDescRegId(record.getDescRegId());
            userService.update(user);
        }
        return new BaseResult(true, res);
    }
    @GetMapping("/current")
    public BaseResult login(HttpServletRequest request) {
        String tk = request.getHeader("tk");
        User user = JWTUtil.getUser(request.getHeader("tk"));
        Category category = new Category();
        category.setType(DataStatus.CATEGORY_DATA_TYPE_VERSION.getVal());

        Category category1 = categoryService.selectLatestOne(category);
        String version = category1==null?"0":category1.getId().toString();
        Map map = new HashMap();
        if(user==null||tk==null){
            map.put("error","token过期或不存咋，请重新登录");
            map.put("password",version);
            return new BaseResult(false,map.toString(),401);
        }
        User managerInfo = userService.findByUsername(user.getUserName());
        managerInfo.setPassword(version);
        return new BaseResult(true,managerInfo);
    }
    @GetMapping("/checkVersion")
    public BaseResult checkVersion(HttpServletRequest request) {
        Category category = new Category();
        category.setType(DataStatus.CATEGORY_DATA_TYPE_VERSION.getVal());
        Category category1 = categoryService.selectLatestOne(category);
        String version = category1==null?"0":category1.getName();
        Map map = new HashMap();
        map.put("version",version);
        return new BaseResult(true,map);
    }

    @PostMapping
    @NoRepeatSubmit
    public BaseResult create(@RequestBody User record) {
        return userService.create(record);
    }

    @PutMapping
    public BaseResult update(@RequestBody User record) {
        return new BaseResult(true, userService.update(record));
    }


    /**
     * 修改个人资料
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/updateInfo")
    public BaseResult updateInfo(@RequestBody User record,HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        record.setId(user.getId());
        return new BaseResult(true, userService.update(record));
    }

    /**
     * 修改密码
     * @param record
     * @param request
     * @return
     */
    @PutMapping("/updatePwd")
    public BaseResult updatePwd(@RequestBody UserVo record,HttpServletRequest request) {
        User user = JWTUtil.getUser(request.getHeader("tk"));
        record.setId(user.getId());
        return userService.updatePwd(record);
    }

    /**
     * 需有删除授权
     * @param id
     * @return
     */
    @RequiresPermissions(PermissionConstant.DELETE_USER)
    @DeleteMapping("/{id}")
    public BaseResult del(@PathVariable Integer id) {
        return userService.del(id);
    }

    @GetMapping("/{id}")
    public BaseResult get(@PathVariable Integer id) {
        return new BaseResult(true, userService.detail(id));
    }

    /**
     * 分页
     *
     * @param record
     * @return
     */
    @GetMapping("/pageWidthAdmin")
    public ListResult page(UserVo record) {
        return userService.page(record);
    }

    @GetMapping("/page")
    public ListResult pageNoAdmin(UserVo record) {
        return userService.pageNoAdmin(record);
    }

    /**
     *
     * @param record
     * @return
     */
    @GetMapping("/pageWidthDepName")
    public ListResult pageWidthDepName(UserVo record) {
        return userService.pageWidthDepName(record);
    }

    /**
     * 根据权限名称,获取用户列表
     * @param record
     * @return
     */
    @GetMapping("/listByPermission")
    public ListResult listByPermission(CategoryVo record) {
        return userService.listByPermission(record);
    }


    /**
     * 列表
     *
     * @param record
     * @return
     */
    @GetMapping
    public ListResult list(UserVo record) {
        return new ListResult(true, userService.list(record));
    }
    @GetMapping("jzMember/{projectId}")
    public ListResult jzMember(@PathVariable Integer projectId) {
        return userService.jzMember(projectId);
    }
}
